<template>
  <basic-container>
    <div class="search_form">
      <el-form ref="form" :model="queryForm" label-width="100px" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="公司简称:">
              <el-input id="id-business-customer-queryForm-name" size="mini" placeholder="请输入公司名称"
                        v-model="queryForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户等级:">
              <el-select id="id-business-customer-queryForm-level" v-model="queryForm.level" clearable
                         filterable size="mini" placeholder="请选择客户等级"
                         style="width: 150px"
                         ref="level" @change="searchForm">
                <el-option label="全部" value=""/>
                <el-option label="T1" value="T1"/>
                <el-option label="T2" value="T2"/>
                <el-option label="T3" value="T3"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态:">
              <el-select id="id-business-customer-queryForm-status" v-model="queryForm.status" clearable
                         filterable size="mini" placeholder="请选择状态"
                         style="width: 150px"
                         ref="status" @change="searchForm">
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户经理:">
              <el-select id="id-business-customer-queryForm-customerManager" v-model="queryForm.customerManager"
                         clearable filterable size="mini" placeholder="请选择客户经理" style="width:100%"
                         ref="customerManager" @change="searchForm">
                <el-option label="全部" value=""/>
                <el-option
                  v-for="item in customerManagerList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="min-width: 160px;display:flex;justify-content:flex-end;float: right">
            <el-tooltip class="item" effect="dark" content="展开全部" placement="top">
              <el-button :class="upIcon" class="search-circle" @click="unfoldIcon"
                         style="margin-right: 10px"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="清空" placement="top">
              <el-button id="id-business-customer-emptyForm" :class="emptyIcon" class="search-circle"
                         @click="emptyForm"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button id="id-business-customer-searchForm" ype="primary" icon="el-icon-search" size="small"
                         @click="searchForm" style="margin-right: 0">
                搜索
              </el-button>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-show="searchConceal">
          <el-col :span="5">
            <el-form-item label="产品名称:">
              <el-select id="id-business-customer-queryForm-productName" v-model="queryForm.productName"
                         clearable filterable size="mini" placeholder="请选择产品名称" style="width:100%"
                         ref="productName" @change="searchForm">
                <el-option label="全部" value=""/>
                <el-option
                  v-for="(item,index) in productNameList"
                  :key="index"
                  :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="联系电话:">
              <el-input v-model="queryForm.phone" placeholder="请输入联系电话" size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="地址:">
              <el-input v-model="queryForm.address" placeholder="请输入地址" size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售经理:">
              <el-select id="id-business-customer-queryForm-salesManager" v-model="queryForm.salesManager" clearable
                         filterable size="mini" placeholder="请选择销售经理"
                         style="width: 150px"
                         ref="salesManager" @change="searchForm">
                <el-option label="全部" value=""/>
                <el-option
                  v-for="item in managerList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-show="searchConceal">
          <el-col :span="5">
            <el-form-item label="创建人:">
              <el-select id="id-business-customer-queryForm-createUser" v-model="queryForm.createUser" clearable
                         filterable size="mini" placeholder="请选择创建人" style="width:100%"
                         ref="offerPlatform" @change="searchForm">
                <el-option label="全部" value=""/>
                <el-option
                  v-for="item in createUserList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="createTime"
                type="daterange"
                size="mini"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <avue-crud :option="option"
               :table-loading="loading"
               :view-name="'customer'"
               :data="data"
               :page.sync="page"
               :before-open="beforeOpen"
               :row-class-name-rollback="getRowClassName"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot-scope="{row}" slot="level">
        <el-button v-if="row.level !== ''" type="danger" circle :style="shouColour(row.level)" style="cursor: default">
          <span style="margin-left: -5px;display: block;margin-top: -4px;">{{ row.level }}</span></el-button>
      </template>
      <template slot-scope="{row}" slot="salesManager">
        <span>{{getSalesManag(row.salesManager)}}</span>
      </template>
      <template slot-scope="{row}" slot="customerManager">
        <span>{{getCustomerManager(row.customerManager)}}</span>
      </template>getCustomerManager
      <template slot-scope="{row}" slot="status">
        <el-select v-model="row.status"
                   size="mini"
                   @change="changeStatus(row)">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </template>
      <template slot-scope="{row}" slot="productName">
        <div style="display: flex">
          <el-select v-model="productNameString(row.productName)[0]"
                     :placeholder="productNameString(row.productName)[0] !== undefined ? '请选择': '无数据'"
                     style="width: 150px;margin-right: 10px" size="mini">
            <el-option
              v-for="(item,index) in productNameString(row.productName)"
              :key="index"
              :value="item">
            </el-option>
          </el-select>
          <el-button size="mini"
                     style="color: #252525;background-color: #fafafa;height: 30px;width: 30px;cursor: default " circle>
            {{ productNameString(row.productName).length }}
          </el-button>
        </div>
      </template>
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   id="id-business-customer-handleAdd"
                   icon="el-icon-plus"
                   plain
                   v-if="permissionList.addBtn"
                   @click="handleAdd">新 增
        </el-button>
        <el-button id="id-business-customer-handleDelete"
                   type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permissionList.delBtn"
                   @click="handleDelete">删 除
        </el-button>
        <el-button id="id-business-customer-handleExport"
                   type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   :disabled="!(selectionList.length > 0)"
                   v-if="permissionList.excelBtn"
                   @click="handleExport">导 出
        </el-button>
        <el-button id="id-business-customer-handleExport"
                   type="success"
                   size="small"
                   plain
                   @click="showProgress">最新进展
        </el-button>
      </template>
      <!--      <template slot-scope="{type,disabled}" slot="offerForm">-->
      <!--        <el-table :data="offerList" style="width: 100%" border class="view-offer-table"  stripe >-->
      <!--          <el-table-column prop="name" label="offer名称"></el-table-column>-->
      <!--          <el-table-column prop="product" label="产品名"></el-table-column>-->
      <!--          <el-table-column prop="state" label="状态">-->
      <!--            <template slot-scope="scope">-->
      <!--              <span-->
      <!--                :style="{color:scope.row.state === 1 ? 'red' : 'green'}"> {{ scope.row.state === 1 ? '关闭' : '开启' }}</span>-->

      <!--            </template>-->
      <!--          </el-table-column>-->
      <!--          <el-table-column prop="product" label="创建日期"></el-table-column>-->
      <!--        </el-table>-->
      <!--      </template>-->
      <template slot-scope="{type,disabled}" slot="offerLabel">
        <span>offer ( {{ offerList.length }} )</span>
      </template>
      <template slot-scope="{row}" slot="orderListTitleForm">
        <div style="margin-right: -100%">
        </div>
      </template>
      <template slot-scope="{row}" slot="orderListForm">
        <div style="margin-left: -50px;margin-right: -100%">
          <customer-offer-list :customerId="row.id"></customer-offer-list>
        </div>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-tooltip content="查看" placement="top">
          <el-button size="small" icon="el-icon-view" type="text" @click="rowView(scope.row,scope.index)"
                     :disabled="!(permissionList.viewBtn)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="编辑" placement="top">
          <el-button icon="el-icon-edit" type="text" @click="rowEdit(scope.row,scope.index)"
                     :disabled="!(permissionList.editBtn&&scope.row.originCustomerId==='')"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="删除" placement="top">
          <el-button icon="el-icon-delete" type="text" @click="rowDel(scope.row,scope.index)"
                     :disabled="!(scope.row.funcFlag != 'used' && permissionList.delBtn &&scope.row.originCustomerId==='')"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>




    <el-drawer size="60%" :title="drawerTitle" :visible.sync="visible" :modal-append-to-body="false"
               style="width:100%;" :close-on-press-escape="false" :wrapperClosable="false"
               :close-on-click-modal="false" :before-close="handlerDrawerClose" :append-to-body="true">
      <el-form ref="form" :model="form" label-width="100px" style="width: 90%;margin: 0 auto" :rules="rules">
        <el-row v-if="drawerTitle === '新 增'">
          <el-col :span="12" >
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" size="mini" placeholder="请选择">
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="display: flex;flex-wrap: wrap">
          <el-col :span="item.span || 12" v-for="(item,index) in option.column" :key="index" v-if="drawerTitle === '查 看'
            ? (item.viewDisplay === false ? false : true) : drawerTitle ==='新 增' ? (item.addDisplay === false ? false : true):
            (item.editDisplay === false ? false : true)">
            <el-form-item :label="item.label" :prop="item.prop">
              <el-select clearable :disabled="drawerTitle === '查 看' || (item.prop === 'level' && !roles.admin)"
                         style="width: 100%" size="mini"
                         v-if="item.type === 'select'" v-model="form[item.prop]">
                <el-option v-for="it in item.dicData" :key="item.props ? it[item.props.value] : it.value"
                           :label="item.props ? it[item.props.label] : it.label"
                           :value="item.props ? it[item.props.value] : it.value"></el-option>
              </el-select>
              <el-switch v-if="item.type === 'switch'" v-model="form[item.prop]" :active-value='1' :inactive-value='0'
                         :disabled="drawerTitle === '查 看'">
              </el-switch>
              <el-input v-if="item.type === 'textarea'" type="textarea" :disabled="drawerTitle === '查 看'" size="mini"
                        v-model="form[item.prop]" :autosize="{ minRows: 5 }" maxlength="500" show-word-limit></el-input>
              <el-input maxlength="100" :disabled="drawerTitle === '查 看'" v-if="item.type === 'input' || !item.type"
                        size="mini"
                        v-model="form[item.prop]"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-button v-if="drawerTitle==='编 辑'">aa</el-button>-->

        <el-row v-if="drawerTitle==='查 看'">
          <div style="margin-top: 10px">节点记录</div>
          <el-divider></el-divider>
          <el-table :data="recordNode" center style="width: 100%;">
            <el-table-column
              prop="status"
              label="状态"
              width="300">
              <template v-slot="{row}">
                {{findStatus(row.status)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="操作时间"
              width="300">
            </el-table-column>
            <el-table-column
              prop="createUserName"
              label="操作人"
              width="300">
            </el-table-column>
          </el-table>
        </el-row>

        <!--评论发表功能-->
        <el-row id="comment" v-if="drawerTitle==='查 看'  && commentPermission">
          <div style="width: 84%;margin-top: 30px;margin-bottom: 40px">
            <div>发表你的评论：</div>
            <div style="margin-top: 0px">
              <el-checkbox v-model="checked" @change="checkPin" style="margin-top: 10px">只看Pin下的评论</el-checkbox>
              <el-button
                id="id-offer-componets-creativecheck-submitMessage"
                class="submit-btn"
                type="primary"
                @click="sendComment"
                size="mini"
                :disabled="comments === ''"
              >发送
              </el-button>
              <quill-editor style="height: 180px;margin-top: 10px" v-model="comments"
                            :options="editorOptions"></quill-editor>
              <!--              <el-input-->
              <!--                id="id-offer-componets-creativecheck-submitMessage-two"-->
              <!--                :autosize="{ minRows: 3}"-->
              <!--                type="textarea"-->
              <!--                placeholder="请输入内容"-->
              <!--                @keyup.enter.native="sendComment"-->
              <!--                v-model="comments"-->
              <!--                :disabled="!commentPermission"-->
              <!--              >-->
              <!--              </el-input>-->
            </div>
          </div>
        </el-row>
        <!--评论查看-->
        <el-row v-if="drawerTitle==='查 看'  && commentPermission">
          <div style="width: 74%; margin-bottom: 40px;">
            <div v-for="(item,index) in commentsData" :key="index" style="margin-top: 10px">
              <div style="height: 20px">
                <div style="width: 20px;height:20px;margin-right: 8px;float: left">
                  <!--                  <img :src="item.avatar" style="width: 100%;height: 100%;border-radius:50%">-->
                  <i class="el-icon-s-custom"></i>
                </div>
                <div style="margin-right: 8px;float: left"><span>{{ item.name }}</span></div>
                <div style="margin-right: 8px;float: left"><span>{{ item.updateTime }}</span></div>
                <div style="margin-right: 8px;float: left">
                  <el-checkbox v-model="item.isPin" @change="changePin(item.isPin,item.id)">Pin</el-checkbox>
                </div>
                <!--                <div v-if="userInfo.userId === item.userId" style="float: right;margin-right: 20px" @click="removeMessage(item.id)">-->
                <!--                  <i class="el-icon-delete"></i>-->
                <!--                </div>-->
              </div>
              <div style="margin-top: 20px; margin-bottom: 30px">
                <div v-html="item.comments"></div>
              </div>
            </div>
            <div v-if="commentPage.size<moreComments" style="margin: 20px;">
              <div style="margin: 0 auto;width: 120px">
                <el-button id="id-offer-componets-creativecheck-getMoreContent" size="mini" style="text-align: center"
                           @click="getMoreContent">
                  查看更多评价
                </el-button>
              </div>
            </div>
            <div v-else style="margin: 0 auto;color: #00a2ff;margin: 20px;text-align: center;">
              到底啦!
            </div>
          </div>
        </el-row>

        <div v-if="drawerTitle !== '查 看'" style="display: flex;justify-content: center">
          <el-button size="mini" type="primary" icon="el-icon-circle-check" @click="handleForm">保存</el-button>
          <el-button size="mini" icon="el-icon-circle-close" @click="handlerDrawerClose">取消</el-button>
        </div>
      </el-form>
    </el-drawer>
    <div id="downloadExcel"></div>
    <el-drawer
      title="最新进展"
      size="800px"
      :visible.sync="progressDailog"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="closeProgressDailog"
      :append-to-body="true"
      :wrapperClosable="false"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <div class="progress-detail-drawer">
          <div class="comment-search">
            <el-form :inline="true" :model="progressSearchForm" class="demo-form-inline">
              <el-form-item label="客户名称" label-width="100">
                <!--                <el-input size="mini" v-model="progressSearchForm.createUsers" placeholder="审批人"></el-input>-->
                <el-select size="mini" v-model="progressSearchForm.createUsers" placeholder="请选择" clearable filterable>
                  <el-option
                    v-for="item in customerList"
                    :key="item.key"
                    :label="item.name"
                    :value="item.key">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="评论时间">
                <el-date-picker
                  v-model="progressSearchForm.commentSearchDate"
                  type="daterange"
                  align="left"
                  size="mini"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions">
                </el-date-picker>
                <!--                <el-date-picker-->
                <!--                  size="mini"-->
                <!--                  v-model="progressSearchForm.commentSearchDate"-->
                <!--                  type="daterange"-->
                <!--                  align="right"-->
                <!--                  unlink-panels-->
                <!--                  range-separator="至"-->
                <!--                  start-placeholder="开始日期"-->
                <!--                  end-placeholder="结束日期">-->
                <!--                </el-date-picker>-->
              </el-form-item>
              <el-form-item style="width: 20px">
                <el-button size="mini" type="primary" @click="getProgressPage">查询</el-button>
              </el-form-item>
            </el-form>
            <!--            <cs-comment-list :data="commentsData" :show-opt="false" @load="loadCommit"></cs-comment-list>-->
            <div style="width: 90%;margin: 0 auto; margin-bottom: 40px;">
              <div v-for="(item,index) in progressData" :key="index" style="margin-top: 10px">
                <div style="height: 30px">
                  <div style="width: 20px;height:20px;margin-right: 8px;float: left">
                    <!--                                      <img :src="item.avatar" style="width: 100%;height: 100%;border-radius:50%">-->
                    <i class="el-icon-s-custom"></i>
                  </div>
                  <div style="margin-right: 8px;float: left"><span>{{ item.title }}</span></div>
                  <div style="margin-right: 8px;float: left"><span>{{ item.updateTime }}</span></div>
                </div>
                <div style="margin-top: 20px; margin-bottom: 30px ;padding-left: 30px">
                  <div v-html="item.comments"></div>
                </div>
              </div>

              <div >
                <div style="margin: 0 auto;width: 120px" v-if="progressPage.size<totalProgress">
                  <el-button id="id-offer-componets-creativecheck-getMoreContent" size="mini" style="text-align: center"
                             @click="getMoreProgress">
                    查看更多进展
                  </el-button>
                </div>
                <div v-else style="text-align: center;color: #00a2ff;margin: 0 auto">到底啦！！！</div>
              </div>
            </div>
          </div>
        </div>
        <template v-slot:bottom>
          <el-button size="mini" @click="closeProgressDailog">关闭</el-button>
        </template>
      </cs-drawer-container>
    </el-drawer>
  </basic-container>
</template>

<script>
import customerOfferList from "./components/customerOfferList"
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  stateUpdate,
  getSalesManager,
  getCustomerManager,
  getCreateUser,
  getComment,
  sendComment,
  changeCommentPin,
  getCommentPermission,
  getNewProgress,
  getStatusRecord
} from "@/api/business/customer";
import {deepClone, exportExcel} from "@/util/util";
import {mapGetters} from "vuex";
import BeetlesTable from "@/components/basic-components/beetles-table";
import {alterStatus} from "../../api/business/customer";
import {getProductName} from "../../api/business/appManager";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import CsCommentList from "@/components/CsCommentList/CsCommentList";
import {getCustomerList} from "@/api/finance/commonApi";

export default {
  components: {
    BeetlesTable,
    customerOfferList,
    CsDrawerContainer,
    CsCommentList
  },
  data() {
    var checkInternationalPhone = (rule, value, callback) => {
      const phoneReg = /^\d+(-\d+)*$/;
      if (value === '') {
        if (rule.required) {
          callback(new Error('请输入电话号码'))
        } else {
          callback();
        }
      } else if (!phoneReg.test(value)) {
        callback(new Error('请输入正确的电话号码!'))
      } else {
        callback()
      }
    }

    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9]+[-_.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[-_.]?)*[a-zA-Z0-9]+(\.[a-zA-Z]{2,})+$/;
      if (value === '') {
        if (rule.required) {
          callback(new Error('请输入公司邮箱'))
        } else {
          callback();
        }
      } else if (!mailReg.test(value)) {
        callback(new Error('请输入正确的邮件格式!'))
      } else {
        callback()
      }
    }
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      recordNode:[],
      moreComments: 0,
      index: 0,
      editData: [],
      productNameList: [],
      upIcon: 'el-icon-arrow-down',
      searchConceal: false,
      rowStatus: [{label: "活跃", value: "1"}, {label: "停止", value: "0"}],
      statusList:[
        {label: "线索", value: 3},
        {label: "获得联系方式", value: 4},
        {label: "首次沟通完成", value: 5},
        {label: "持续跟踪", value: 6},
        {label: "无合作机会", value: 7},
        {label: "暂停跟踪", value: 8},
        {label: "活跃", value: 1},
        {label: "停止", value: 0}
      ],
      rules: {
        // status:  {required: true, message: '请选择状态', trigger: 'change'}
      },
      form: {},
      createTime: [],
      progressContent: '',
      editorOptions: {
        placeholder: '请输入评论',
        modules: {
          toolbar: {
            container: [['bold', 'italic', 'underline', 'strike'], ['image']]
          }
        },
      },
      queryForm: {
        name: '',
        salesManager: '',
        customerManager: '',
        createUser: '',
        level: '',
        status: '',
        productName: [],
        phone: '',
        address: '',
        startDate: '',
        endDate: ''
      },
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      emptyIcon: 'el-icon-delete',
      drawerTitle: '',
      visible: false,
      managerList: [],
      selectionList: [],
      customerManagerList: [],
      createUserList: [],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        menuWidth: 120,
        //excelBtn:true,
        selection: true,
        dialogClickModal: false,
        dialogWidth: 1200,
        column: [
          {
            label: "公司全称",
            prop: "fullName",
            rules: [{
              required: true,
              message: "请输入公司名称",
              trigger: "change"
            }],
            overHidden: true,
            fixed: true,

          },
          {
            label: "公司简称",
            prop: "name",
            rules: [{
              required: true,
              message: "请输入公司名称",
              trigger: "change"
            }],
            overHidden: true,
            fixed: true,
          },
          {
            label: "销售经理",
            prop: "salesManager",
            type: 'select',
            dicData: [],
            // dicUrl: '/api/blade-user/select-user?roleAlias=sales_manager',
            props: {
              label: "realName",
              value: "id"
            },
            // dataType: 'string',
            rules: [{
              required: true,
              message: "请选择销售经理",
              trigger: "change"
            }],
            filterable: true,
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            hide: false,
            overHidden:true,
            slot:true,
          },
          {
            label: "客户经理",
            prop: "customerManager",
            type: 'select',
            dicData: [],
            slot:true,
            props: {
              label: "realName",
              value: "id"
            },
            // dataType: 'string',
            // rules: [{
            //   required: true,
            //   message: "请选择客户经理",
            //   trigger: "change"
            // }],
            slot:true,
            filterable: true,
            addDisplay: true,
            viewDisplay: true,
            editDisplay: true,
            hide: false,
            overHidden:true
          },
          {
            label: "客户等级",
            prop: "level",
            type: "select",
            dicData: [{label: "T1", value: "T1"}, {label: "T2", value: "T2"}, {label: "T3", value: "T3"}],
            rules: [{
              required: true,
              message: "请选择等级",
              trigger: "change"
            }],
          },
          {
            label: "状态",
            prop: "status",
            type: 'select',
            width: 100,
            addDisplay: false,
            dicData: [
              {label: "线索", value: 3},
              {label: "获得联系方式", value: 4},
              {label: "首次沟通完成", value: 5},
              {label: "持续跟踪", value: 6},
              {label: "无合作机会", value: 7},
              {label: "暂停跟踪", value: 8},
              {label: "活跃", value: 1},
              {label: "停止", value: 0}
            ]
            // dicData: this.statusList
          },
          {
            label: "产品名称",
            prop: "productName",
            width: 250,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "联系电话",
            prop: "phone",
            placeholder: "请输入联系电话",
            rules: [{
              required: false,
              validator: checkInternationalPhone,
              trigger: "change"
            }],
            overHidden:true
          },
          {
            label: "公司邮箱",
            prop: "email",
            placeholder: "请输入公司邮箱",
            rules: [{
              required: false,
              validator: checkEmail,
              trigger: "change"
            }],
            overHidden: true,
          },
          {
            span: 24,
            label: "地址",
            prop: "address",
            placeholder: "请输入公司地址",
            rules: [{
              required: false,
              message: "请输入地址",
              trigger: "change"
            }],
            overHidden: true,
          },
          {
            span: 24,
            label: "备注",
            prop: "remark",
            type: 'textarea',
            overHidden:true
          },
          {
            label: "创建人",
            prop: "createUser",
            type: 'select',
            dicUrl: '/api/blade-user/select/user?statusList=0,1,2&isAll=true',
            props: {
              label: "realName",
              value: "id"
            },
            filterable: true,
            addDisplay: false,
            editDisplay: false,
            overHidden:true,
          },
          {
            label: "创建时间",
            prop: "createTime",
            addDisplay: false,
            editDisplay: false,
            overHidden:true
          },
          // {
          //   label: "客户订单",
          //   prop: "orderListTitle",
          //   addDisplay: false,
          //   viewDisplay: true,
          //   editDisplay: false,
          //   showColumn: false,
          //   row: true,
          //   hide: false,
          //   formslot: true,
          // },
          {
            label: "",
            prop: "orderList",
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false,
            showColumn: false,
            row: true,
            hide: false,
            formslot: true,
          },
        ]
      },
      data: [],
      currOpRowId: '',
      offerList: [],
      //评论数据
      commentsData: [],
      customerId: '',
      commentPage: {
        current: 1,
        size: 10,
      },
      isPin: false,
      comments: '',
      checked: false,
      commentPermission: '',
      // 进展弹窗
      progressDailog: false,
      // 评论搜索
      customerList:[],
      progressSearchForm: {
        createUsers: '',
        commentSearchDate: null,
      },
      progressData: [],
      progressPage: {
        current: 1,
        size: 30,
      },
      totalProgress:0,
      totalCommentsData:0,
    };
  },
  computed: {
    ...mapGetters(["permission", "roles", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.customer_add || this.permission.cooperation_add, false),
        viewBtn: this.vaildData(this.permission.customer_view || this.permission.partner_view, false),
        delBtn: this.vaildData(this.permission.customer_delete || this.permission.cooperation_delete, false),
        editBtn: this.vaildData(this.permission.customer_edit || this.permission.cooperation_edit, false),
        excelBtn: this.vaildData(this.permission.customer_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  created() {
    getProductName().then(res => {
      this.productNameList = res.data.data
    })
    let columnLevel = ['level']
    columnLevel.forEach(level => {
      let levelFields = this.findObject(this.option.column, level)
      if (levelFields != null && levelFields != -1 && !this.roles.admin) {
        if (levelFields.rules) {
          levelFields.rules.forEach(rule => {
            rule.required = false
          })
        }
      }
    })
    this.init();
    //客户信息-新增界面，除了公司名称外，其他都改成非必填  （针对ads4each这个代理商租户：定制321600）
    let clearRequiredTenantList = ['321600'];
    if (clearRequiredTenantList.includes(this.userInfo.tenant_id)) {
      let columnsToClearRules = ['email', 'phone', 'address'];
      columnsToClearRules.forEach((columnName) => {
        let column = this.findObject(this.option.column, columnName);
        if (column != null && column != -1) {
          if (column.rules) {
            column.rules.forEach(rule => {
              rule.required = false;
            })
          }
        }
      })
    }
    if (this.userInfo.is_agency == 0) {
      this.option.column.forEach((c) => {
        if (c.prop == 'salesManager' || c.prop == 'customerManager') {
          c.search = false;
          c.hide = true;
          c.addDisplay = false;
          c.viewDisplay = false;
          c.editDisplay = false;
          c.rules.forEach((rule) => {
            rule.required = false;
          })
        }
      });
    }
    this.buildSearch();
    if (this.$route.query.type === '1') {
      this.progressSearchForm.createUsers = this.$route.query.id
      this.showProgress()
    }
  },
  mounted() {
    // 最新进展
    if (this.$route.query.type === '1') {
      this.progressSearchForm.createUsers = this.$route.query.id
      this.showProgress()
    }
  },
  methods: {
    getSalesManag(val){
      try {
        return this.managerList.find(item=>item.id == val)['realName']
      } catch (e) {
        return ''
      }
    },
    getCustomerManager(val){
      try {
        return this.customerManagerList.find(item=>item.id == val)['realName']
      } catch (e) {
        return ''
      }
    },
    findStatus(val){
      return  this.statusList.find(item=>item.value===val)['label']
    },
    unfoldIcon() {
      if (this.upIcon === 'el-icon-arrow-down') {
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      } else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    shouColour(level) {
      if (level === 'T1') {
        return "color:'#fff3ff';background-color:#ff3b30;width:30px;height:30px;display:block"
      } else if (level === 'T2') {
        return "color:'#fff3ff';background-color:#ff9502;width:30px;height:30px"
      } else {
        return "color:'#fff3ff';background-color:#ffc9a6;border-color: #ffc9a6;width:30px;height:30px"
      }
    },
    productNameString(productName) {
      let nameList = []
      if (productName !== '') {
        nameList = productName.split(",")
      }
      return nameList
    },
    changeStatus(row) {
      alterStatus(row).then(() => {
        this.$message.success("状态已修改")
      })
    },
    formatHtml(origin) {
      return origin.replace(/\n|\r/g, '<br/>')
    },
    statusTableList() {
      return [
        {label: '活跃', value: 1},
        {label: '停止', value: 0}
      ]
    },
    /**
     * 新增
     */
    handleAdd() {
      this.optionRules()
      this.form = {
        phone: '',
        email: '',
        status: 3
      }
      this.option.column.find(item=> item.label=='客户经理').dicData=this.customerManagerList;
      this.option.column.find(item=> item.label=='销售经理').dicData=this.managerList
      this.drawerTitle = '新 增';
      this.visible = true;
    },
    /**
     * 查看
     */
    rowView(row) {
      console.log(row)
      getStatusRecord(row.id).then(res=>{
        console.log(res)
        this.recordNode = res.data.data
      })
      this.form = row;
      this.option.column.find(item=> item.label=='客户经理').dicData=this.customerManagerList;
      this.option.column.find(item=> item.label=='销售经理').dicData=this.managerList
      // console.log(row)
      // this.form.status = this.statusList.find(item=>item.value===row.status)['label']
      this.beforeOpen();
      this.drawerTitle = '查 看';
      this.visible = true;
      this.customerId = row.id
      this.getCommnet()
      this.getCommentPermission()
    },
    /**
     * 编辑
     */
    rowEdit(row) {
      this.option.column.find(item=> item.label=='客户经理').dicData=this.customerManagerList;
      this.option.column.find(item=> item.label=='销售经理').dicData=this.managerList
      this.rules = {}
      this.form = deepClone(row);
      this.beforeOpen();
      this.drawerTitle = '编 辑';
      this.visible = true;
      this.optionRules()

    },
    /**
     * 新增/编辑判断条件
     */
    optionRules() {
      this.option.column.map(item => {
        if (item.rules) {
          let rule = {[item.prop]: item.rules}
          this.rules = Object.assign(this.rules, rule)
        }
      })
    },
    init() {
      getSalesManager().then(res => {
        this.managerList = res.data.data
      })
      getCustomerManager().then(res => {
        this.customerManagerList = res.data.data
      })
      getCreateUser().then(res => {
        this.createUserList = res.data.data
      })
    },
    buildSearch() {
      if (this.createTime === '' || this.createTime === null) {
        this.queryForm.startDate = ''
        this.queryForm.endDate = ''
      } else if (this.createTime !== '') {
        this.queryForm.startDate = this.createTime[0]
        this.queryForm.endDate = this.createTime[1]
      }
      this.query = {...this.queryForm};
    },
    searchForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buildSearch();
          this.page.currentPage = 1
          this.onLoad(this.page)
        }
      });
    },
    /**
     * 关闭抽屉
     */
    handlerDrawerClose() {
      this.visible = false;
      this.refreshChange()
      this.checked = false
    },
    //清楚按钮函数
    emptyForm() {
      this.queryForm = {
        name: '',
        salesManager: '',
        customerManager: '',
        createUser: '',
        level: '',
        status: '',
        productName: '',
        phone: '',
        address: '',
        startDate: '',
        endDate: ''
      }
      this.createTime = []
      this.searchForm();
    },
    //修改状态
    changeState(e, id) {
      stateUpdate(id).then((res) => {
        if (res.data.code === 200) {
          this.$message.success('状态修改成功!')
        }
      })
    },
    handleForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.drawerTitle === '新 增') {
            this.rowSave();
          } else {
            this.rowUpdate();
          }
        }
      });
    },
    rowSave() {
      // console.log(this.form)
      if(this.form.status===1 && this.form.customerManager===undefined){
        return this.$message.warning('活跃状态下必须选择客户经理！')
      }
      console.log('form',this.form)
      add(this.form).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.visible = false;
      }, error => {
        window.console.log(error);
      });
    },
    rowUpdate() {
      console.log(this.form)
      if(this.form.status===1 && this.form.customerManager===''){
        return this.$message.warning('活跃状态下必须选择客户经理！')
      }
      update(this.form).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.visible = false;
      }, error => {
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      let deleteIds = [];
      this.selectionList.forEach(ele => {
        if (ele.funcFlag != 'used') {
          deleteIds.push(ele.id);
        }
      });
      if (deleteIds.length === 0) {
        this.$message.warning("请选择至少一条允许删除的客户数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(deleteIds.join(","));
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    async beforeOpen(type) {
      if (["edit", "view"].includes(type)) {
        this.currOpRowId = this.form.id;
        await getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          if (this.form.salesManager == -1) this.form.salesManager = null;
          if (this.form.customerManager == -1) this.form.customerManager = null;
        });
        // if (["view"].includes(type)) {
        //   this.offerList = [
        //     {name: '上海怡鸿', product: '上海怡鸿', state: 0},
        //     {name: '上海怡鸿', product: '上海怡鸿', state: 0},
        //     {name: '上海怡鸿', product: '上海怡鸿', state: 1},
        //   ]
        // }
      }
    },
    searchReset() {
      this.emptyForm();
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign({}, params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.data.forEach((row) => {
          if (row.salesManager == -1) {
            row.salesManager = '';
          }
          if (row.customerManager == -1) {
            row.customerManager = '';
          }
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    handleExport() {
      this.$confirm("是否导出客户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let tableData = {
          title: null,
          headers: [],
          rowList: [],
          bottom: [],
        };
        tableData.headers.push({data: '公司名称', style: 'text-align: right;'});
        tableData.headers.push({data: '销售经理', style: 'text-align: right;'});
        tableData.headers.push({data: '客户经理', style: 'text-align: right;'});
        tableData.headers.push({data: '客户等级', style: 'text-align: right;'});
        tableData.headers.push({data: '状态', style: 'text-align: right;'});
        tableData.headers.push({data: '产品名称', style: 'text-align: right;'});
        tableData.headers.push({data: '联系电话', style: 'text-align: right;'});
        tableData.headers.push({data: '公司邮箱', style: 'text-align: right;'});
        tableData.headers.push({data: '地址', style: 'text-align: right;'});
        tableData.headers.push({data: '备注', style: 'text-align: right;'});

        this.selectionList.forEach(row => {
          let colList = [];
          colList.push({data: row.name, style: 'text-align: right;'});
          colList.push({data: row.$salesManager, style: 'text-align: right;'});
          colList.push({data: row.$customerManager, style: 'text-align: right;'});
          colList.push({data: row.level, style: 'text-align: right;'});
          colList.push({data: (row.status === 0) ? '停止' : '活跃', style: 'text-align: right;'});
          colList.push({data: row.productName, style: 'text-align: right;'});
          colList.push({data: row.phone, style: 'text-align: right;'});
          colList.push({data: row.email, style: 'text-align: right;'});
          colList.push({data: row.address, style: 'text-align: right;'});
          colList.push({data: row.remark, style: 'text-align: right;'});
          tableData.rowList.push(colList);
        });
        exportExcel('downloadExcel', tableData.title, tableData.headers, tableData.rowList, tableData.bottom, '客户数据表.xls');
      });
    },
    getRowClassName({row}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    async changePin(isPin, id) {
      await changeCommentPin({isPin: isPin, id: id})
    },
    async checkPin() {
      // this.isPin=!this.isPin
      if (this.checked === true) {
        const {data: res} = await getComment(this.customerId, this.commentPage, true)
        // console.log('res111',res)
        // if(res.code!==200)return this.$message.error('获取评论列表失败')
        this.commentsData = res.data.records
      } else {
        const {data: res} = await getComment(this.customerId, this.commentPage)
        // console.log('res111',res)
        // if(res.code!==200)return this.$message.error('获取评论列表失败')
        this.commentsData = res.data.records
      }
    },
    async getCommentPermission() {
      const {data: res} = await getCommentPermission(this.customerId)
      console.log('res111', res)
      if (res.code === 200) this.commentPermission = res.data
    },

    async getCommnet() {
      const {data: res} = await getComment(this.customerId, this.commentPage)
      console.log('res111', res)
      if (res.code !== 200) return this.$message.error('获取评论列表失败')
      this.commentsData = res.data.records
      this.moreComments = res.data.total
    },
    async sendComment() {
      const {data: res} = await sendComment({customerId: this.customerId, comments: this.comments})
      // console.log('res111',res)
      if (res.code === 200) {
        this.comments = ''
        this.getCommnet()
        return this.$message.success('发布评论成功');


      } else {
        return this.$message.error('发布评论失败')
      }
    },
    async getMoreContent() {
      this.commentPage.size += 5
      if (this.checked === true) {
        const {data: res} = await getComment(this.customerId, this.commentPage, true)
        // console.log('res111',res)
        // if(res.code!==200)return this.$message.error('获取评论列表失败')
        this.commentsData = res.data.records
      } else {
        this.getCommnet()
      }
    },
    // 显示最新进展
    showProgress() {
      getCustomerList().then(res => {
        this.customerList = res.data.data
      })
      this.getProgressPage()
      this.progressDailog = true
    },
    closeProgressDailog(){
      this.progressDailog = false
      this.progressSearchForm.createUsers=''
      this.progressSearchForm.commentSearchDate=null
    },

    getProgressPage(){
      getNewProgress(
        this.progressSearchForm.createUsers,
        this.progressPage,
        this.progressSearchForm.commentSearchDate ? this.progressSearchForm.commentSearchDate[0]+ ' 00:00:00' : '',
        this.progressSearchForm.commentSearchDate ? this.progressSearchForm.commentSearchDate[1]+ ' 00:00:00' : ''
      ).then(res=>{
        console.log(res)
        this.progressData = res.data.data.records
        this.totalProgress = res.data.data.total
      })
    },
    getMoreProgress(){
      this.progressPage.size+=10
      this.getProgressPage()
    }
  }
};
</script>

<style lang="scss">
.search_form {
  /deep/ .el-form-item {
    margin-bottom: 0;
  }
}

.view-offer-table {
  margin-top: 40px;

  /deep/ .el-table td, .el-table th {
    padding: 9px 0;
  }
}
</style>
<style lang="scss" scoped>
/deep/ .current-op-row {
  background-color: #f5dab1;
}

/deep/ .el-input__inner {
  text-overflow: ellipsis;
}

.progress-detail-drawer {
  padding: 0 20px;
}
</style>

